package com.hs.springboot_demo.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.springboot_demo.common.Result;
import com.hs.springboot_demo.domain.News;
import com.hs.springboot_demo.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author d-will
 * @create 2022--03--03 10:18
 */
@RestController
@RequestMapping("/news")
public class NewsController {
	@Autowired
	NewsService newsService;

	@PostMapping("/save")
	public Result save(@RequestBody News news) {
		news.setTime(DateUtil.date());
		boolean b = newsService.saveOrUpdate(news);
		if (b) {
			return Result.success();
		} else {
			return Result.error(1, "失败");
		}
	}

	@RequestMapping("getAll")
	@ResponseBody
	public List getAll() {
		// ArrayList<Object> list = new ArrayList<>();
		List<News> list1 = newsService.list();
		return list1;
	}

	@GetMapping("/findPage")
	public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
	                       @RequestParam(defaultValue = "10") Integer pageSize,
	                       @RequestParam(defaultValue = "") String search) {
		Page<News> page = new Page<>(pageNum, pageSize);
		// userService.page(page, Wrappers.<User>lambdaQuery().like(User::getNickname,search));
		QueryWrapper<News> wrapper = new QueryWrapper<>();
		if (StrUtil.isNotBlank(search)) {
			wrapper.like("title", search);
		}
		Page<News> page1 = newsService.page(page, wrapper);
		return Result.success(page1);
	}

	@GetMapping("/delById")
	public Result delById(@RequestParam Integer id) {
		boolean b = newsService.removeById(id);
		if (b) {
			return Result.success();
		} else {
			return Result.error(0, "失败了");
		}
	}


}
